const axios = require('axios');

async function testFixedJoinActivity() {
  try {
    console.log('=== 测试修复后的活动参与功能 ===');
    
    // 测试未登录用户参与活动（应该测试用新注册用户）
    console.log('\n1. 注册一个新用户进行测试...');
    try {
      const registerResponse = await axios.post('http://localhost:3000/api/auth/register', {
        username: 'testuser' + Date.now(),
        email: 'test' + Date.now() + '@example.com',
        password: 'password123'
      });
      
      const newUserToken = registerResponse.data.token;
      console.log('新用户注册成功');
      
      // 测试参与活动
      console.log('\n2. 新用户尝试参与活动2...');
      try {
        const joinResponse = await axios.post('http://localhost:3000/api/activities/2/join', {}, {
          headers: {
            'Authorization': `Bearer ${newUserToken}`,
            'Content-Type': 'application/json'
          }
        });
        console.log('✅ 参与活动成功:', joinResponse.data);
        
        // 测试重复参与（应该返回400）
        console.log('\n3. 测试重复参与（应该失败）...');
        try {
          await axios.post('http://localhost:3000/api/activities/2/join', {}, {
            headers: {
              'Authorization': `Bearer ${newUserToken}`,
              'Content-Type': 'application/json'
            }
          });
          console.log('❌ 重复参与应该失败但成功了');
        } catch (error) {
          if (error.response?.status === 400) {
            console.log('✅ 重复参与正确返回400:', error.response.data.error);
          } else {
            console.log('❌ 重复参与返回了意外的错误状态:', error.response?.status);
          }
        }
        
        // 测试取消参与
        console.log('\n4. 测试取消参与...');
        try {
          const leaveResponse = await axios.post('http://localhost:3000/api/activities/2/leave', {}, {
            headers: {
              'Authorization': `Bearer ${newUserToken}`,
              'Content-Type': 'application/json'
            }
          });
          console.log('✅ 取消参与成功:', leaveResponse.data);
        } catch (error) {
          console.log('❌ 取消参与失败:', error.response?.data);
        }
        
      } catch (error) {
        if (error.response?.status === 500) {
          console.log('❌ 仍然出现500错误:', error.response?.data);
        } else {
          console.log('其他错误:', error.response?.status, error.response?.data);
        }
      }
      
    } catch (error) {
      console.error('注册新用户失败:', error.response?.data);
    }
    
    // 测试多个并发请求
    console.log('\n5. 测试并发参与活动...');
    const promises = [];
    for (let i = 0; i < 3; i++) {
      promises.push(
        axios.post('http://localhost:3000/api/auth/login', {
          email: 'alice@student.com',
          password: 'password123'
        }).then(loginRes => {
          return axios.post('http://localhost:3000/api/activities/3/join', {}, {
            headers: {
              'Authorization': `Bearer ${loginRes.data.token}`,
              'Content-Type': 'application/json'
            }
          });
        }).catch(err => err.response)
      );
    }
    
    const results = await Promise.all(promises);
    results.forEach((result, index) => {
      if (result.data) {
        console.log(`  并发请求${index + 1}: ${result.status} - ${result.data.message || result.data.error}`);
      }
    });
    
  } catch (error) {
    console.error('测试过程中发生错误:', error.message);
  }
}

testFixedJoinActivity(); 